const express = require('express');
const router = express.Router();
const { pool } = require('../config/database');
const { authMiddleware, adminMiddleware } = require('./auth');
const dayjs = require("dayjs")
// 获取借阅记录列表
router.get('/', authMiddleware, async (req, res) => {
  try {
    const { user_id, status, page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    let query = `
      SELECT b.*, books.title, books.author, books.isbn
      FROM borrows b
      JOIN books ON b.book_id = books.id
    `;
    let params = [];

    // 非管理员只能查看自己的借阅记录
    if (req.user.role === 'user') {
      query += ' WHERE b.user_id = ?';
      params.push(req.user.id);
    } else if (user_id) {
      query += ' WHERE b.user_id = ?';
      params.push(user_id);
    }

    if (status) {
      query += params.length ? ' AND' : ' WHERE';
      query += ' b.status = ?';
      params.push(status);
    }

    query += ' ORDER BY b.borrow_date DESC LIMIT ? OFFSET ?';
    params.push(Number(limit), Number(offset));

    const [borrows] = await pool.execute(query, params);
    const [total] = await pool.execute('SELECT COUNT(*) as count FROM borrows');

    // res.json(response(0, '成功', {
    //   borrows,
    //   total: total[0].count,
    //   page: Number(page),
    //   totalPages: Math.ceil(total[0].count / limit)
    // }));

    res.json({
      code: 0,
      msg: "获取借阅记录列表成功",
      data: {
        borrows,
        total: total[0].count,
        page: Number(page),
        totalPages: Math.ceil(total[0].count / limit)
      }
    })
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 借阅图书
router.post('/', authMiddleware, async (req, res) => {
  try {
    const { book_id, due_date, comment } = req.body;
    const newTime = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
    // 检查图书是否存在且有可用副本
    const [books] = await pool.execute(
      'SELECT * FROM books WHERE id = ? AND available_copies > 0',
      [book_id]
    );

    if (books.length === 0) {
      return res.status(400).json({ code: -1, msg: '图书不可用', data: {} });
    }

    // 检查用户是否已借阅该图书
    const [existing] = await pool.execute(
      'SELECT * FROM borrows WHERE user_id = ? AND book_id = ? AND status = "borrowed"',
      [req.user.id, book_id]
    );

    if (existing.length > 0) {
      return res.status(400).json({ code: -1, msg: '您已借阅此图书', data: {} });
    }

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 创建借阅记录
      await connection.execute(
        'INSERT INTO borrows (user_id, book_id, due_date, borrow_date, comment) VALUES (?, ?, ?, ?, ?)',
        [req.user.id, book_id, due_date, newTime, comment]
      );

      // 更新图书可用副本数
      await connection.execute(
        'UPDATE books SET available_copies = available_copies - 1 WHERE id = ?',
        [book_id]
      );
      // 记录操作日志
      await connection.execute(
        'INSERT INTO system_logs (user_id, action, description) VALUES (?, ?, ?)',
        [req.user.id, 'borrow_book', `用户借书:book_id: ${book_id},user_id: ${req.user.id}`]  // 使用实际的newUserId
      );
      await connection.commit();
      res.status(201).json({ code: 0, msg: '借阅成功', data: {} });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 归还图书
router.put('/:id/return', authMiddleware, async (req, res) => {
  try {
    // 检查借阅记录是否存在
    // console.log("req.params.idreq.params.id",req.params.id)
    const [borrows] = await pool.execute(
      'SELECT * FROM borrows WHERE book_id = ? AND user_id = ? AND status = "returned"',
      [req.params.id, req.user.id]
    );
    console.log("borrowsborrows", borrows)
    if (borrows.length !== 0) {
      return res.status(404).json({ code: -1, msg: '借阅记录不存在或已归还', data: {} });
    }

    const borrow = borrows[0];

    // 非管理员只能归还自己借的书
    if (req.user.role === 'user' && borrow.user_id !== req.user.id) {
      return res.status(403).json({ code: -1, msg: '没有权限', data: {} });
    }

    // 开启事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 更新借阅记录
      await connection.execute(
        'UPDATE borrows SET status = "returned", return_date = CURRENT_TIMESTAMP WHERE user_id = ? AND book_id = ?',
        [req.user.id, req.params.id]
      );

      // 更新图书可用副本数
      await connection.execute(
        'UPDATE books SET available_copies = available_copies + 1 WHERE id = ?',
        [req.params.id]
      );

      // 记录操作日志
      await connection.execute(
        'INSERT INTO system_logs (user_id, action, description) VALUES (?, ?, ?)',
        [req.user.id, 'return_book', `用户还书:book_id: ${req.params.id},user_id: ${req.user.id}`]  // 使用实际的newUserId
      );

      await connection.commit();
      res.json({ code: 0, msg: '成功', data: { code: 0, msg: '归还成功', data: {} } });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 获取借阅统计信息（管理员权限）
router.get('/statistics', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const [totalBorrows] = await pool.execute('SELECT COUNT(*) as count FROM borrows');
    const [activeBorrows] = await pool.execute('SELECT COUNT(*) as count FROM borrows WHERE status = "borrowed"');
    const [overdueBorrows] = await pool.execute('SELECT COUNT(*) as count FROM borrows WHERE status = "overdue"');

    res.json({
      code: 0, msg: '成功', data: {
        total: totalBorrows[0].count,
        active: activeBorrows[0].count,
        overdue: overdueBorrows[0].count
      }
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 图书借书时间延期
router.put("/:id/delayed", authMiddleware, async (req, res) => {
  const book_id = req.params.id;
  const { delayed_at } = req.body;
  const user_id = req.user.id;

  // 参数验证
  if (!book_id || !delayed_at) {
    return res.status(400).json({
      code: -1,
      msg: "缺少必要的参数：书籍ID或延期日期"
    });
  }

  try {
    // 1. 检查借阅记录是否存在
    const [borrowRecord] = await pool.execute(
      `SELECT due_date, status, return_date 
       FROM borrows 
       WHERE book_id = ? AND user_id = ?`,
      [book_id, user_id]
    );

    if (borrowRecord.length === 0) {
      return res.status(404).json({
        code: -1,
        msg: "未找到该用户的借阅记录"
      });
    }

    const currentDueDate = borrowRecord[0].due_date;
    const currentStatus = borrowRecord[0].status;
    const returnDate = borrowRecord[0].return_date;

    // 2. 检查书籍是否已归还
    if (currentStatus === 'returned' || returnDate) {
      return res.status(400).json({
        code: -1,
        msg: "该书已归还，无法延期"
      });
    }

    // 3. 验证延期日期
    const delayedDate = dayjs(delayed_at);
    if (!delayedDate.isValid()) {
      return res.status(400).json({
        code: -1,
        msg: "延期日期格式无效"
      });
    }

    if (delayedDate.isBefore(dayjs())) {
      return res.status(400).json({
        code: -1,
        msg: "延期时间不能早于当前时间"
      });
    }

    if (delayedDate.isBefore(dayjs(currentDueDate))) {
      return res.status(400).json({
        code: -1,
        msg: "延期时间不能早于当前到期时间"
      });
    }

    // 4. 更新到期日
    const [updateResult] = await pool.execute(
      `UPDATE borrows SET due_date = ? 
       WHERE book_id = ? AND user_id = ?`,
      [delayed_at, book_id, user_id]
    );

    if (updateResult.affectedRows === 0) {
      return res.status(500).json({
        code: -1,
        msg: "更新失败"
      });
    }

    // 记录操作日志
    await pool.execute(
      'INSERT INTO system_logs (user_id, action, description) VALUES (?, ?, ?)',
      [req.user.id, 'delayed_book', `用户续借图书:book_id: ${book_id},user_id: ${req.user.id},续借至${delayed_at}`]  // 使用实际的newUserId
    );

    res.json({
      code: 0,  // 成功应该用0表示
      msg: "延期成功",
      data: {
        due_date: delayed_at
      }
    });

  } catch (error) {
    console.error("延期处理错误:", error);
    res.status(500).json({
      code: -1,
      msg: '服务器内部错误',
      data: {}
    });
  }
});
module.exports = router;